package org.beetl.online;

import org.beetl.core.*;
import org.beetl.core.engine.OnlineTemplateEngine;
import org.beetl.core.exception.BeetlException;
import org.beetl.core.exception.ErrorInfo;
import org.beetl.core.resource.StringTemplateResourceLoader;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
public class OnlineController {
	GroupTemplate groupTemplate;

	@PostMapping("/render")
	public String render(String json,String input){
		if(input.length()>250||json.length()>100){
			return "输入内容过长";
		}

		Map jsonParas = null;
		if(json!=null){
			Script script = groupTemplate.getScript(json);
			script.execute();
			if(!script.isSuccess()){
				return "执行输入脚本出错:"+getErrorMsg(script.getErrorInfo());
			}
			jsonParas = script.getResult();
		}


		Template template = groupTemplate.getTemplate(input);
		template.binding(jsonParas);
		try{
			String ret = template.render();
			return ret;
		}catch(BeetlException exception){
			ErrorInfo errorInfo = new ErrorInfo(exception);
			return "执行模板出错:"+getErrorMsg(errorInfo);
		}

	}



	protected String getErrorMsg(ErrorInfo errorInfo){
		return errorInfo.toString();
	}

	@PostConstruct
	protected  void init() throws IOException {
		StringTemplateResourceLoader loader = new StringTemplateResourceLoader();
		groupTemplate = new GroupTemplate(loader, Configuration.defaultConfiguration());
		groupTemplate.setEngine(new OnlineTemplateEngine());
		groupTemplate.setErrorHandler(new ReThrowConsoleErrorHandler());
		groupTemplate.setNativeSecurity(new WhiteListNativeSecurityManager());
	}
}
